package com.googlecode.bipol.war.services;

import java.io.Serializable;

import com.googlecode.bip.dao.DAOFactory;
import com.googlecode.bip.dao.UserDAO;
import com.googlecode.bip.entity.IGenericUser;
import com.googlecode.bip.entity.IUser;
import com.googlecode.bipol.war.session.IBipSession;

public class UserManagerImpl implements UserManager, Serializable {
    private final static long serialVersionUID = 2L;
    private IBipSession bipSession;

    public UserManagerImpl( final IBipSession bipSession )
    {
        this.bipSession = bipSession;
    }

    @Override
    public IGenericUser getGenericUser()
    {
        return bipSession.getGenericUser();
    }

    @Override
    public IUser createUser(String username, String password) throws ServiceException {
        final UserDAO   dao     = DAOFactory.getDAOFactory().getUserDAO();
        IUser           iUser;

        try {
            // FIXME: Check that user does not exists yet
            // CC-NOTE: For security reason not method is provided to
            // check if a user exists.
            // Two solutions:
            // 1. Try if fail then user exist
            // 2. Test result of: IGenericUser ifNullNotExist = dao.findGenericUser( username, password );

            iUser = dao.insertUser(username, password);
            }
        catch (Exception e) {
            throw new ServiceException("Error when creating account: "+e.getMessage(), e);
            }

        if( iUser == null ) {
            throw new ServiceException("User already exits !");
            }

        return iUser;
    }

}
